package com.yuzhihao.writejvm.run;

import com.yuzhihao.writejvm.clazz.ClassInfo;
import com.yuzhihao.writejvm.format.ClassFormatEnum;
import lombok.extern.log4j.Log4j2;

import java.io.*;
import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * 解析并打印class文件信息
 *
 * @author yzh
 */
@Log4j2
public class ParseRun {

    public static final Queue<ClassFormatEnum> QUEUE = new LinkedBlockingDeque<>();

    static {
        QUEUE.offer(ClassFormatEnum.magic);
        QUEUE.offer(ClassFormatEnum.minor_version);
        QUEUE.offer(ClassFormatEnum.major_version);
        QUEUE.offer(ClassFormatEnum.cps);
        QUEUE.offer(ClassFormatEnum.access_flags);
        QUEUE.offer(ClassFormatEnum.this_class);
        QUEUE.offer(ClassFormatEnum.super_class);
        QUEUE.offer(ClassFormatEnum.interfaces);
        QUEUE.offer(ClassFormatEnum.fields);
        QUEUE.offer(ClassFormatEnum.methods);
        QUEUE.offer(ClassFormatEnum.attributes);
    }

    /**
     * 获取类信息
     * @param path
     * @return
     */
    public static ClassInfo getClass(String path) {
        try (DataInputStream dis = new DataInputStream(new FileInputStream(path))) {
            ClassInfo info = new ClassInfo();

            ClassFormatEnum poll = QUEUE.poll();
            do {
                poll.parse(dis, info);
                poll = QUEUE.poll();
            } while (Objects.nonNull(poll));

            System.out.println(info);

            return info;
        } catch (IOException e) {
            log.error("文件：{}解析异常：",path,e);
        }
        return null;
    }

    public static void main(String[] args){
//        String classfile = "/Users/yzh/aliyun/java/yuzhihaolearn/jvm1/target/classes/jvm/parse/ParseClass.class";
//        String classfile = "/Users/yzh/aliyun/java/yuzhihaolearn/jvm1/target/classes/jvm/parse/InterfaceTest.class";
//        String classfile = "/Users/yzh/aliyun/java/yuzhihaolearn/jvm1/target/classes/jvm/info/Studet.class";
//        String classfile = "/Users/yzh/aliyun/java/yuzhihaolearn/jvm1/target/classes/jvm/info/Cat.class";
        String classfile = "/Users/yzh/aliyun/java/detect-sys/service/target/classes/com/fjzn/detect/service/detect/collect/calc/DetectDataImpl.class";
//        String classfile = "/Users/yzh/aliyun/java/yuzhihaolearn/jvm1/target/classes/jvm/info/JvmTest.class";
//        String classfile = "/Users/yzh/aliyun/java/yuzhihaolearn/jvm1/target/classes/jvm/parse/ParseClassSwitch.class";

        getClass(classfile);

    }

}
